package com.offcn.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

public class TokenDecode {

    // 引入公钥
    private static final String PUBLIC_KEY = "public.key";

    /**
     * 读取公钥的数据
     */
    private static String getPublicKey(){
        ClassPathResource resource = new ClassPathResource(PUBLIC_KEY);
        try (
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        ){
            String publicKey = bufferedReader.readLine();
            return publicKey;
        } catch(IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析令牌
     */
    public static Map<String,String> decodeToken(String token) {
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(getPublicKey()));
        String claims = jwt.getClaims();
        return JSON.parseObject(claims,Map.class);
    }

    /**
     * 获取用户名
     */
    public static String getUsername(String token){
        Map<String, String> map = decodeToken(token);
        String username = map.get("user_name");
        return username;
    }
}
